import {Injectable, signal} from '@angular/core';

export interface Field {
  id: string;
  name: string;
  type: string;
  primaryKey?: boolean;
  foreignKey?: boolean;
  notNull?: boolean;
  unique?: boolean;
  increment?: boolean;
  comment?: string;
}

export interface Table {
  id: string;
  name: string;
  x: number;
  y: number;
  fields: Field[];
  color?: string;
  comment?: string;
}

export interface Relationship {
  id: string;
  fromTable: string;
  toTable: string;
  fromField: string;
  toField: string;
  type: 'one-to-one' | 'one-to-many' | 'many-to-many';
}

@Injectable({
  providedIn: 'root'
})
export class TablesService {
  private _tables = signal<Table[]>([]);

  readonly tables = this._tables.asReadonly();

  // 表格相关功能
  // 获取单个表格
  getTable(id: string): Table | undefined {
    return this._tables().find(table => table.id === id);
  }

  // 添加表格
  addTable(table: Table) {
    this._tables.update(tables => [...tables, table]);
  }

  updateTable(id: string, updates: Partial<Table>) {
    this._tables.update(tables =>
      tables.map(table =>
        table.id === id ? {...table, ...updates} : table
      )
    );
  }

  removeTable(id: string) {
    this._tables.update(tables => tables.filter(table => table.id !== id));
  }

  // 字段相关
  // 获取单个字段
  getField(tableId: string, fieldId: string): Field | undefined {
    const table = this.getTable(tableId);
    return table?.fields.find(field => field.id === fieldId);
  }

  addField(tableId: string, field: Field) {
    this._tables.update(tables =>
      tables.map(table =>
        table.id === tableId
          ? {...table, fields: [...table.fields, field]}
          : table
      )
    );
  }

  updateField(tableId: string, fieldId: string, updates: Partial<Field>) {
    this._tables.update(tables =>
      tables.map(table =>
        table.id === tableId
          ? {
            ...table,
            fields: table.fields.map(field =>
              field.id === fieldId ? {...field, ...updates} : field
            )
          }
          : table
      )
    );
  }

  removeField(tableId: string, fieldId: string) {
    this._tables.update(tables =>
      tables.map(table =>
        table.id === tableId
          ? {
            ...table,
            fields: table.fields.filter(field => field.id !== fieldId)
          }
          : table
      )
    );
  }

  // 字段排序
  reorderFields(tableId: string, oldIndex: number, newIndex: number) {
    this._tables.update(tables =>
      tables.map(table => {
        if (table.id === tableId) {
          const fields = [...table.fields];
          const [removed] = fields.splice(oldIndex, 1);
          fields.splice(newIndex, 0, removed);
          return {...table, fields};
        }
        return table;
      })
    );
  }

  // 批量更新字段
  updateFields(tableId: string, fields: Field[]) {
    this.updateTable(tableId, {fields});
  }

  clearTables() {
    this._tables.set([]);
  }
}
